package com.auth.manage.datasource.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.crypto.Data;
import java.util.Date;

@Configuration
public class DataSourceConfiguration {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());  // 乐观锁
        mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());  // 防止全表删除/更新
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());  // 分页插件
        return mybatisPlusInterceptor;
    }

    // 自动填充公共字段
    @Bean
    public MetaObjectHandler metaObjectHandler(){
        // this指实现MetaObjectHandler接口的类(匿名内部类)的一个实例对象
        // MetaObject对应我们传参的Entity对象，每次执行Insert/Update之前，MP会回调这里
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("deleted", 0, metaObject);  // 逻辑删除字段默认为0
                this.setFieldValByName("lockVersion", 0, metaObject);  // 乐观锁字段默认为0
                this.setFieldValByName("createTime", new Date(), metaObject);
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
            // 如果有手动传值，就不进行默认填充:迁移另一张表的数据到当前表时，批量插入时，时间是基于那张表的时间而不是当前时间
            public void setFieldValByNameIfNull(String fieldName, Object fieldVal, MetaObject metaObject){
                if (metaObject.getValue(fieldName) == null) this.setFieldValByName(fieldName, fieldVal, metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        };
    }

}
